<?php
namespace Admin\Controller;
use Admin\Model\AttributeModel;
use Think\Controller;
use Org\Util\Rbac;
use Org\Net\UploadFile;

/**
 * 封装大部分共用的Action 定义Rbac权限
 * Class CommonController
 * @package Admin\Controller
 */
class CommonController extends Controller {

    function __construct  () {

        parent::__construct();
        $this->init();
        $this->assign('avatar',getUserName('','avatar',false));
    }

    /**
     * 初始化
     * 验证权限
     */
    function _initialize() {
        if (! $_SESSION[C('USER_AUTH_KEY')]) {
            $this->redirect('Public/login');
        }

        // 用户权限检查
        if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
            if (!RBAC::AccessDecision()) {
                //检查认证识别号
                if (!$_SESSION [C('USER_AUTH_KEY')]) {
                    //跳转到认证网关
                    redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
                }
                // 没有权限 抛出错误
                if (C('RBAC_ERROR_PAGE')) {
                    // 定义权限错误页面
                    redirect(C('RBAC_ERROR_PAGE'));
                } else {
                    if (C('GUEST_AUTH_ON')) {
                        $this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
                    }
                    // 提示错误信息
                    $this->error(L('_VALID_ACCESS_'));
                }
            }
        }

    }

    /**
     * 主页面
     */
    function index() {
        //列表过滤器，生成查询Map对象
        // $map = $this->_search ();
        $map = array();
        // if (method_exists ( $this, '_filter' )) {
        // 	$this->_filter ( $map );
        // }

        $model = D (CONTROLLER_NAME);
         if (! empty ( $model )) {
            $model = $model->where($map)->select();
            $this->assign ( 'lists', $model );
         }


        $this->display ();
        return;
    }

    /**
     * 插入
     */
    function insert() {

        $model = D (CONTROLLER_NAME);

        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

        public function checkLogin() {
            //检查当前操作是否需要认证
            if(RBAC::checkAccess()) {
                //检查认证识别号
                if(!$_SESSION[C('USER_AUTH_KEY')]) {
                    if(C('GUEST_AUTH_ON')) {
                        // 开启游客授权访问
                        if(!isset($_SESSION['_ACCESS_LIST']))
                            // 保存游客权限
                            RBAC::saveAccessList(C('GUEST_AUTH_ID'));
                    }else{
                        // 禁止游客访问跳转到认证网关
                        redirect(PHP_FILE.C('USER_AUTH_GATEWAY'));
                    }
                }
            }
            return true;
        }


	    /**-----------------------------------------------------
		 * 默认删除操作---------------------------------------------------------
		 * @access public----------------------------------------------------------
		 * @return string----------------------------------------------------------
		 * @throws ThinkExecption----------------------------------------------------------
		 */
		public function delete() {
			//删除指定记录

			$model = M (CONTROLLER_NAME);
			if (! empty ( $model )) {
				$pk = $model->getPk ();
				$id = $_REQUEST [$pk];
				if (isset ( $id )) {
					$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
					$list=$model->where ( $condition )->setField ( 'status', - 1 );
					if ($list!==false) {
						$this->success ('删除成功！' );
					} else {
						$this->error ('删除失败！');
					}
				} else {
					$this->error ( '非法操作' );
				}
			}
		}

    /**
     *  多选删除
     */
        public function multiDelete() {
            $model = M (CONTROLLER_NAME);
            if (! empty ( $model )) {
                $pk = $model->getPk ();
                $ids = $_REQUEST ['ids'];
                if (isset ( $ids )) {
                    $condition = array ($pk => array ('in', explode ( ',', $ids ) ) );
                    $list=$model->where ( $condition )->delete();

                    if ($list!==false) {
                        $this->success ('删除成功！','',true );
                    } else {
                        $this->error ('删除失败！','',true);
                    }
                } else {
                    $this->error ( '非法操作','',true );
                }
            }
        }

    /**
     * 编辑页面
     */
    function edit() {

        $model = M ( CONTROLLER_NAME );
        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        $this->assign ( 'vo', $vo );
        $this->display();
    }

    /**
     * 修改
     */
    function update() {

        $model = D ( CONTROLLER_NAME );
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }

        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            //成功提示
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }
    }

    /**
     * 删除指定数据
     */
    public function foreverdelete() {
        //删除指定记录
        $model = D (CONTROLLER_NAME);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $id = $_REQUEST [$pk];
            if (isset ( $id )) {
                $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
                if (false !== $model->where ( $condition )->delete ()) {
                    $this->success ('删除成功！');
                } else {
                    $this->error ('删除失败！');
                }
            } else {
                $this->error ( '非法操作' );
            }
        }

    }

    /**
     * 验证是否登录
     */
    private function checkUser() {
        if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->error('没有登录',C('DO_MAIN').__APP__.'Public/login/');
        }
    }

    /**
     * 初始化系统 验证访问权限
     */
    function init() {
        $this->checkUser();
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            //显示菜单项
            $curruntNote = CONTROLLER_NAME;  //当前的节点
            $menu  = array();
            if (isset($_SESSION['one_menu'.$_SESSION[C('USER_AUTH_KEY')]])) {
                //如果已经缓存，直接读取缓存
                $menu   =   $_SESSION['one_menu'.$_SESSION[C('USER_AUTH_KEY')]];
            } else {
                //读取数据库模块列表生成菜单项
                $node    =   D("Node");
                $id	=	$node->getField("id");
                $where['level'] = 2;
                $where['status'] = 1;
                $where['pid'] = $id;
                $list	=	$node->where($where)->field('id,name,group_id,title')->order('sort asc')->select();
                $accessList = $_SESSION['_ACCESS_LIST'];
                foreach($list as $key=>$module) {
                  // if(isset($accessList[strtoupper(APP_NAME)][strtoupper($module['name'])]) || $_SESSION['administrator']) {
                        //设置模块访问权限
                        $module['access'] =   1;
                        if (strtolower($module['name']) == strtolower($curruntNote)) {
                            $module['currunt'] = true;
                        }
                        $menu[$module['group_id']][$key]  = $module;
                  //  }
                }
                //缓存菜单访问
                $_SESSION['one_menu'.$_SESSION[C('USER_AUTH_KEY')]]	=	$menu;

            }
            $this->assign('currunt_group',$curruntNote);
            $this->assign('currunt_note',$curruntNote);

            if(!empty($_GET['tag'])){
                $this->assign('menuTag',$_GET['tag']);
            }

            $groups = D("Group")->where(array('group_menu'=>"{$_GET['menu']}",'status'=>"1"))->order("sort asc ")->select();

            //去掉用户组 菜单
            if( getSiginRoleName() != 'core'  ){
                unset($groups[0]);
            }
            $this->assign("groups",$groups);
            $this->assign('menu',$menu);

        }

        C('SHOW_RUN_TIME',false);			// 运行时间显示
        C('SHOW_PAGE_TRACE',false);
    }

    /**
     *----------------------------------------------------------
     * 默认禁用操作
     *
     *----------------------------------------------------------
     * @access public
     *----------------------------------------------------------
     * @return string
     *----------------------------------------------------------
     * @throws FcsException
     *----------------------------------------------------------
     */
    public function forbid() {

        $model = D (CONTROLLER_NAME);
        $pk = $model->getPk ();
        $id = $_REQUEST [$pk];
        $condition = array ($pk => array ('in', $id ) );
        $list=$model->forbid ( $condition );
        if ($list!==false) {
           // $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '状态禁用成功','',true );
        } else {
            $this->error  (  '状态禁用失败！','',true );
        }
    }

    /**
     *----------------------------------------------------------
     * 默认恢复操作
     *----------------------------------------------------------
     * @access public
     * @return string-------------------------------------------------------
     * @throws FcsException----------------------------------------------------------
     */
    function resume() {
        //恢复指定记录

        $model = D (CONTROLLER_NAME);
        $pk = $model->getPk ();
        $id = $_GET [$pk];
        $condition = array ($pk => array ('in', $id ) );
        if (false !== $model->resume ( $condition )) {
            $this->success ( '状态恢复成功！','',true  );
        } else {
            $this->error ( '状态恢复失败！','',true  );
        }
    }


    /**
     * 上传文件 （默认上传图片）
     * @param $path
     * @param string $size
     * @param string $rule
     * @param string $allow
     * @return string
     *
     */
    public function uploadImage($path,$size = '10000000000',$rule = 'uniqid',$allow = '',$flag = false) {

        if($_FILES){
            $upload = new UploadFile();// 实例化上传类
            $upload->saveRule = $rule;//上传文件的命名规则
            $upload->maxSize  = $size ;// 设置附件上传大小
            if ($allow) {
                $upload->allowExts  = $allow;
            } else {
                $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg','ico');// 设置附件上传类型
            }
            if(!$flag){
                $upload->savePath =  $_SERVER['DOCUMENT_ROOT']. $path;// 设置附件上传目录
            } else {
                $upload->savePath =  $_SERVER['DOCUMENT_ROOT'].substr(__ROOT__,strpos(__ROOT__,'/')+1).$path;
            }
            if(!$upload->upload()) {// 上传错误提示错误信息
                $this->error($upload->getErrorMsg());
            }else{// 上传成功
                $info = $upload->getUploadFileInfo();
                $url= $path.$info[0]['savename'];
                if (!$flag){
                    return $url;
                }
                else{
                    return $saveData = array(
                       'name' => $info[0]['savename'],
                       'url'  => $url= $path.$info[0]['savename']
                    );
                }
            }
        }
    }


    public function setExportExcelData(array $data)
    {
        $this->excel_data_list = $data;
    }

    public function getExportExcelData()
    {
        return $this->excel_data_list;
    }


    public function setExportFields(array $data)
    {
        $this->export_fields = $data;
    }

    public function getExportFields()
    {
        return $this->export_fields;
    }
    public function setExportModel($model)
    {
        $this->export_model = $model;
    }

    public function getExportModel()
    {
        return $this->export_model;
    }

    public function setExportFileName($filename)
    {
        $this->export_file_name = $filename;
    }

    public function getExportFileName()
    {
        return $this->export_file_name;
    }

    /**
     * 导出excel
     * @param string $key
     * @param null $params
     * @param null $childtitle
     */
    public function exportExcel($key="id",$params=null,$childtitle=null)
    {
        $model = $this->getExportModel();
        $field = $this->getExportFields();
        $keys=array_keys ($field);

        if(!$params){
            $params = $_REQUEST ['ids'];
        }
        $map[$key]  = array('in',$params);

        if(!$model){
            $model=D(CONTROLLER_NAME);
        }else{
            $model=D($model);
        }
        if(!$this->getExportExcelData()){
            $list=$model->field($keys)->where($map)->order("id desc")->select();
        }else{
            $list=$this->getExportExcelData();
        }
        foreach ($keys as $k){
            if(isset($field[$k]['callback'])){

                foreach ($list as $key=>$val){
                    $list[$key][$k]=call_user_func($field[$k]['callback'],$val[$k],$field[$k]['params']);
                }
            }
            $last_array[]=$field[$k]['label'];
        }
        $filename = date('Y-m-d',time());
        if($this->getExportFileName()) $filename = $this->getExportFileName();
        if ($childtitle!=null){
            $content = $this->fetchExcel($list, $last_array,$childtitle);
        } else {
            $content = $this->fetchExcel($list, $last_array);
        }
        $filename=$filename.'.xls';
        $this->downloadfile($content,$filename);
    }

    /**
     * 导出定制格式（双标题）的excel
     * @param $cols
     * @param $fristNode
     */
    public function exportProfitExcel($cols,$fristNode)
    {
        $field = $this->getExportFields();
        $list = '';
        if($this->getExportExcelData()){
            $list=$this->getExportExcelData();
        }

        $filename = date('Y-m-d',time());
        if($this->getExportFileName()) $filename = $this->getExportFileName();

        $html='<table><tr><td></td>';
        foreach ($field as $val){
            $html.='<td>'.L($val).'</td>';
        }
        $html.='</tr>';
         for($i =0; $i<count($cols); $i++){
                $html.='<tr>';
                 if (in_array($i,$fristNode)):
                     $html.=' <td style="text-align: left"><b>'.L($cols[$i]).'</b></td> ';
                else:
                    $html.=' <td style="text-align: right">'.L($cols[$i]).'</td> ';
                endif;

                for($j=0;$j<count($field);$j++) {
                    if ( $list[$i][$j] ):

                        $html.=' <td class="text-center">'.number_format($list[$i][$j],2).'</td> ';
                     else:
                         $html.=' <td></td>';
                    endif;
                }
             $html.='</tr>';
         }
        $html.='</table>';

        $filename=$filename.'.xls';
        $this->downloadfile($html,$filename);
    }

    /**
     * 下载文件
     * @param $content  string 下载内容
     * @param string $file  文件名字加后缀
     */
    function downloadfile($content, $file='newfile.xls'){
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=$file");
        $ext = substr(end(explode('.', $file)), 0, 3);
        switch($ext){
            case 'doc' :
                $html = '<html xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"
                 xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"xmlns="http://www.w3.org/TR/REC-html40">';
                $html .= '<head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /></head>';
                break;
            case 'xls':
                $html = '<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
                $html .= '<head><meta http-equiv="Content-type" content="text/html;charset=UTF-8" /><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:Selected/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
                break;
            case 'zip':
             //   header("Content-Type: application/zip"); //zip格式的
                header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
                header('Content-Length: '. filesize($content)); //告诉浏览器，文件大小
                @readfile($content);
                return;
                break;
        }
        echo $html . '<body>'.$content .'</body></html>';

    }

    function fetchExcel($data,$title,$childtitle = null)
    {
        $html='<table><tr>';
        foreach ($title as $val){
            $html.='<td>'.$val.'</td>';
        }
        $html.='</tr>';
        if ($childtitle != null){
            $html .='<tr>';
            foreach ($childtitle as $v){
                $html.='<td>'.$v.'</td>';
            }
            $html .='</tr>';
        }
        foreach($data as $key=>$item){
            $html.='<tr>';
            foreach ($item as $v){
                if(is_numeric($v)&&strlen($v)>=10)
                    $html.='<td style="vnd.ms-excel.numberformat:@">'.$v.'</td>';
                else
                    $html.='<td>'.$v.'</td>';
            }
            $html.='</tr>';
        }
        $html.='</table>';
        return $html;
    }

    /**
     * PHPEXCEL类 多Sheet导出
     * @param $filename
     * @param $listarr
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    function setPHPExcelExport($filename,$listarr){
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
        header('Cache-Control: max-age=0');
        Vendor('phpexcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        foreach ($listarr as $key => $item) {
            if (count($item)) {
                $msgWorkSheet = new \PHPExcel_Worksheet($objPHPExcel, 'card_message' . $key); //创建一个工作表
                $objPHPExcel->addSheet($msgWorkSheet); //插入工作表
                $objPHPExcel->setActiveSheetIndex($key); //切换到新创建的工作表

                $arrExcelInfo = eval('return ' . iconv('gbk', 'utf-8', var_export($item, true)) . ';'); //将数组转换成utf-8
                $objPHPExcel->getActiveSheet()->fromArray(
                    $arrExcelInfo, // 赋值的数组
                    NULL, // 忽略的值,不会在excel中显示
                    'A1' // 赋值的起始位置
                );
            }
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
        $objWriter->save('php://output');

        $objPHPExcel->disconnectWorksheets();
        unset($objPHPExcel);
        exit;
    }

    /**
     * 获取当前节点id
     * @return mixed|string
     */
    public  function getCurrentNodeId() {
        $where['name'] = CONTROLLER_NAME;
        $where['level'] = 2;
        $where['status'] = 1;
        $result = M('Node')->where($where)->getField('id');
        return  $result?$result:'';

    }

    /**
     * 获取指定模块的属性列表数据
     * @param string $nodeID
     * @return array
     */
    public function getAttributeListData($nodeID ='') {

        $nodeID?$where['node_id'] = $nodeID: $where['node_id'] = $this->getCurrentNodeId();
        $list = M('Attribute')->field('attr_id,attr_name,attr_label')->where($where)->order('sort_order')->select();
        $data = array();

        $model = new AttributeModel();
        foreach ($list as $key => $val) {
            $data [$key]  = $val;
            $values = $model->getValues($data[$key]['attr_id']);
            $new = array();
            foreach($values as $k => $v) {
                $new[] = array('id'=>$v['id'],'value'=>$v['attr_value']);
            }
            $data [$key]['attr_values']  = $new;
        }
        return $data;
    }



}